package com.nananren.aop;

import com.nananren.anno.ExceptionLogLog;
import com.nananren.common.MyThreadLocal;
import com.nananren.domain.ExceptionLog;
import com.nananren.exception.CustomerException;
import com.nananren.service.ExceptionLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class ExceptionLogAspect {

    @Autowired
    private ExceptionLogService exceptionLogService;

//    @Pointcut("@annotation(com.nananren.anno.ExceptionLogLog))")
//    public void pt(){}

    @Pointcut("execution(* com.nananren.controller.*.*(..))")
    public void pt2(){}

    @AfterThrowing(value = "pt2()", throwing = "ex")
    public void test(JoinPoint joinPoint, Throwable ex) {

        // 获得操作人id
        Long operateExceptionUserId = MyThreadLocal.getLocal();

        // 获得异常发生时间
        LocalDateTime exceptionCreateTime = LocalDateTime.now();

        // 获得异常类型
        String exceptionType = ex.getClass().getName();

        // 获得异常方法名
        String exceptionMethod = joinPoint.getSignature().getName();

        // 获得异常类名
        String exceptionClass = joinPoint.getTarget().getClass().getName();

        // 获得方法传入的参数
        Object[] args = joinPoint.getArgs();
        String exceptionArgs = Arrays.toString(args);

        // 获得异常描述
        String exceptionDescription = ex.getMessage();

        // 创建异常对象
        ExceptionLog exceptionLog = new ExceptionLog(null, operateExceptionUserId, exceptionCreateTime,
                exceptionType, exceptionMethod, exceptionClass, exceptionArgs, exceptionDescription);
        log.info("exceptionLog:{}", exceptionLog.toString());
        // 插入日志
        exceptionLogService.save(exceptionLog);
    }
}
